package com.jianggujin.demo.admin.handler;

import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jianggujin.modulelink.magager.JModuleManager;

import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Method;
import fi.iki.elonen.NanoHTTPD.Response;

public abstract class AbstractHandler implements Handler {

    protected abstract Object handle(JModuleManager manager, IHTTPSession session, Map<String, String> params)
            throws Exception;

    @Override
    public Response handle(JModuleManager manager, IHTTPSession session) throws Exception {
        Method method = session.getMethod();
        if (Method.POST == method || Method.PUT == method) {
            session.parseBody(null);
        }
        @SuppressWarnings("deprecation")
        Object result = handle(manager, session, session.getParms());
        return NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "application/json", JSON.toJSONString(result));
    }

    protected JSONObject error(String msg) {
        JSONObject result = new JSONObject();
        result.put("errCode", "1");
        result.put("errMsg", msg);
        return result;
    }

    protected JSONObject success(Object data) {
        JSONObject result = new JSONObject();
        result.put("errCode", "0");
        result.put("data", data);
        return result;
    }
}
